﻿using AutoMapper;
using B.MES.Customer.Domain;
using B.MES.Customer.Domain.DTO;
using B.MES.Customer.Infrastructure.IRepository;
using Mysqlx.Crud;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace B.MES.Customer.Infrastructure.Repository
{
    public class ProductRepository : BaseRepository<Product>, IProductRepository
    {
        /// <summary>
        /// 用于连接和操作数据库接口
        /// </summary>
        private readonly ISqlSugarClient _db;
        private readonly IMapper _mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="db">用于连接和操作数据库接口</param>
        public ProductRepository(ISqlSugarClient db, IMapper mapper) : base(db)
        {
            _db = db;
            _mapper = mapper;
        }

        /// <summary>
        /// 绑定产品属性表的下拉框
        /// ISqlSugarClient 实例
        /// </summary>
        /// <returns>返回产品属性表数据</returns>
        public List<Matattribute> GetProductShow()
        {
            return _db.Queryable<Matattribute>().ToList();
        }

        /// <summary>
        /// 绑定产品类别表的下拉框
        /// </summary>
        /// <returns>返回产品类别表数据</returns>
        public List<MatTypeinfo> GetProductinfoShow()
        {
            return _db.Queryable<MatTypeinfo>().ToList();
        }
        /// <summary>
        /// 绑定产品单位表的下拉框

        /// </summary>
        /// <returns>返回产品单位表数据</returns>
        public List<MatUnitInfo> GetProductUnitInfoShow()
        {
            return _db.Queryable<MatUnitInfo>().ToList();
        }
        /// <summary>
        /// 获取所有产品(异步)
        /// </summary>
        /// <returns> 产品集合 </returns>
        public async Task<List<Product>> GetAllProductsAsync()
        {
            return await _db.Queryable<Product>().ToListAsync();
        }

        /// <summary>
        /// 添加产品
        /// </summary>
        /// <param name="productDTO"></param>
        /// <returns></returns>
        public APIResult<ProductDTO> AddProduct(ProductDTO productDTO)
        {
            APIResult<ProductDTO> result = new APIResult<ProductDTO>();

            try
            {
                // 将仓库名称列表连接成一个字符串，以逗号隔开
                // string warehouseNames = string.Join(",", stockIn.WarehouseName);

                //string deserializedStockIn = JsonConvert.SerializeObject(warehouseNames);

                // 添加入库记录，并将级联的仓库名称存储到数据库
                Product Product = new Product
                {
                    Alert_Days = productDTO.Alert_Days,
                    Brand = productDTO.Brand,
                    Maximum_Stock_Quantity = productDTO.Maximum_Stock_Quantity,
                    Minimum_Stock_Quantity = productDTO.Minimum_Stock_Quantity,
                    Model_Number = productDTO.Model_Number,
                    Product_Attributes_Id = productDTO.Product_Attributes_Id,
                    Product_Category_Id = productDTO.Product_Category_Id,
                    Product_Code = productDTO.Product_Code,
                    Product_Expiry_Date = productDTO.Product_Expiry_Date,
                    Product_Image = productDTO.Product_Image,
                    Product_Name = productDTO.Product_Name,
                    Status = productDTO.Status,
                    Remarks = productDTO.Remarks,
                    Unit_Id = productDTO.Unit_Id,
                    Unit_Price = productDTO.Unit_Price,
                };

                var id = _db.Insertable(Product).ExecuteReturnIdentity();

                if (id > 0)
                {
                    result.Success();
                }
                else
                {
                    result.Message = "添加失败";
                }
            }
            catch (Exception ex)
            {
                result.Message = "产品添加出现异常：" + ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 显示产品列表
        /// </summary>
        /// <param name="product_Name">产品名称</param>
        /// <param name="model_Number">规格型号</param>
        /// <param name="brand">品牌</param>
        /// <param name="page">页码</param>
        /// <param name="size">页容量</param>
        /// <returns></returns>
        public PageApiResut<ProductDTO> GetUserListByKeyword(string? product_Name, string? model_Number, string? brand, int page, int size)
        {
            try
            {
                PageApiResut<ProductDTO> pageApiResut = new PageApiResut<ProductDTO>();

                var query = _db.Queryable<Product>();
                var mlist = _db.Queryable<Matattribute>();
                var mtlist = _db.Queryable<MatTypeinfo>();
                var mulist = _db.Queryable<MatUnitInfo>();

                var count = _db.Queryable<Product>().Count();

                //var productList = _db.Queryable<Product>()
                //    .WhereIF(!string.IsNullOrEmpty(product_Name), x => x.Product_Name.Contains(product_Name))
                //    .WhereIF(!string.IsNullOrEmpty(model_Number), x => x.Model_Number.Contains(model_Number))
                //    .WhereIF(!string.IsNullOrEmpty(brand), x => x.Brand.Contains(brand))
                //    .ToPageList(page, size).ToList();

                var list = _db.Queryable<Product, Matattribute, MatTypeinfo, MatUnitInfo>((p, m, mt, mu) => new JoinQueryInfos(
                    JoinType.Inner, p.Product_Attributes_Id == m.AttId,
                    JoinType.Inner, p.Product_Category_Id == mt.TypeId,
                    JoinType.Inner, p.Unit_Id == mu.UnitId
                ))
                .Select((p, m, mt, mu) => new ProductDTO
                {
                    Product_Id = p.Product_Id,
                     Unit_Id= mu.UnitId,
                    Product_Attributes_Id = m.AttId,
                    Product_Category_Id = mt.TypeId,
                    Alert_Days = p.Alert_Days,
                    Brand = p.Brand,
                    Maximum_Stock_Quantity = p.Maximum_Stock_Quantity,
                    Minimum_Stock_Quantity = p.Minimum_Stock_Quantity,
                    Model_Number = p.Model_Number,
                    Product_Code = p.Product_Code,
                    Product_Expiry_Date = p.Product_Expiry_Date,
                    Product_Image = p.Product_Image,
                    Product_Name = p.Product_Name,
                    Status = p.Status,
                    Remarks = p.Remarks,
                    Unit_Price = p.Unit_Price,
                    AttName = m.AttName,
                    TypeName = mt.TypeName,
                    UnitName = mu.UnitName
                }).WhereIF(!string.IsNullOrEmpty(product_Name), p => p.Product_Name.Contains(product_Name))
                  .WhereIF(!string.IsNullOrEmpty(model_Number), p => p.Model_Number.Contains(model_Number))
                  .WhereIF(!string.IsNullOrEmpty(brand), p => p.Brand.Contains(brand)).ToPageList(page, size).OrderByDescending(x => x.Product_Id).ToList();

                // 输出查询条件
                Console.WriteLine($"product_Name: {product_Name}, model_Number: {model_Number}, brand: {brand}");

                // 输出查询到的结果数量
                Console.WriteLine($"Query result count: {list.Count}");

                // 输出具体查询结果
                foreach (var item in list)
                {
                    Console.WriteLine(item.Product_Name);
                }

                var totalCount = count;

                var result = new PageApiResut<ProductDTO>
                {
                    TotalCount = totalCount,
                    Data = list
                };
                return result;
            }
            catch (Exception ex)
            {
                // 输出异常信息
                Console.WriteLine($"An error occurred: {ex.Message}");
                throw;
            }
        }

        /// <summary>
        /// 删除产品信息
        /// </summary>
        /// <param name="product_Id"></param>
        /// <returns></returns>
        public APIResult<Product> DeleteData(int product_Id)
        {
            APIResult<Product> result = new APIResult<Product>();

            try
            {
                // 使用 SqlSugarClient 的 Delete 方法删除数据
                var deleteResult = _db.Deleteable<Product>().Where(it => it.Product_Id == product_Id).ExecuteCommand();

                if (deleteResult > 0)
                {
                    result.Code = 200;
                    result.Message = "删除成功";
                }
                else
                {
                    result.Code = 0;
                    result.Message = "删除失败，未找到匹配的数据";
                }
            }
            catch (Exception ex)
            {
                result.Message = "删除数据时发生异常：" + ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 产品反填
        /// </summary>
        /// <param name="product_Id"></param>
        /// <returns></returns>
        public APIResult<ProductListDTO> GetStockInSel(int product_Id)
        {
            APIResult<ProductListDTO> apiResult = new APIResult<ProductListDTO>();
            try
            {
                var stockIn = _db.Queryable<Product, Matattribute, MatTypeinfo, MatUnitInfo>((p, m, mt, mu) => new JoinQueryInfos(
                     JoinType.Inner, p.Product_Attributes_Id == m.AttId,
                     JoinType.Inner, p.Product_Category_Id == mt.TypeId,
                     JoinType.Inner, p.Unit_Id == mu.UnitId
                 ))
                 .Select((p, m, mt, mu) => new ProductListDTO
                 {
                     Product_Id = p.Product_Id,
                     Alert_Days = p.Alert_Days,
                     Brand = p.Brand,
                     Maximum_Stock_Quantity = p.Maximum_Stock_Quantity,
                     Minimum_Stock_Quantity = p.Minimum_Stock_Quantity,
                     Model_Number = p.Model_Number,
                     Product_Attributes_Id = p.Product_Attributes_Id,
                     Product_Category_Id = p.Product_Category_Id,
                     Product_Code = p.Product_Code,
                     Product_Expiry_Date = p.Product_Expiry_Date,
                     Product_Image = p.Product_Image,
                     Product_Name = p.Product_Name,
                     Status = p.Status,
                     Remarks = p.Remarks,
                     Unit_Id = p.Unit_Id,
                     Unit_Price = p.Unit_Price,
                     AttName = m.AttName,
                     TypeName = mt.TypeName,
                     UnitName = mu.UnitName
                 }).Where(p => p.Product_Id == product_Id)
                    .First();   
                if (stockIn != null)
                {
                    //ProductListDTO productListDTO = _mapper.Map<ProductListDTO>(stockIn[0].Product_Id);

                    //ProductDTO productDto = _mapper.Map<ProductDTO>(stockIn[0]); // 取第一个返回值进行映射

                    //List<Product> stockIns = _db.Queryable<Product>().Where(x => x.Product_Id == product_Id).ToList();

                    //ProductListDTO requestUserDTO = stockIn.First();

                    return new APIResult<ProductListDTO>
                    {
                        Code = 200,
                        Data = stockIn,
                        Message = "反填成功",
                    };
                }
                else
                {
                    return new APIResult<ProductListDTO>
                    {
                        Code = 400,
                        Data = null,
                        Message = "反填失败"
                    };
                }
            }
            catch (Exception ex)
            {
                throw new Exception("查询产品失败", ex);
            }
        }

        /// <summary>
        /// 产品修改
        /// </summary>
        /// <param name="productDTO"></param>
        /// <returns></returns>
        public APIResult<ProductDTO> UpdateProductSel(ProductDTO productDTO)
        {
            APIResult<ProductDTO> apiResult = new APIResult<ProductDTO>();

            try
            {
                // 查询要修改的产品数据
                var productToUpdate = _db.Queryable<Product>().First(x => x.Product_Id == productDTO.Product_Id);

                if (productToUpdate != null)
                {
                    // 更新用户数据
                    productToUpdate.Alert_Days = productDTO.Alert_Days;
                    productToUpdate.Brand = productDTO.Brand;
                    productToUpdate.Maximum_Stock_Quantity = productDTO.Maximum_Stock_Quantity;
                    productToUpdate.Minimum_Stock_Quantity = productDTO.Minimum_Stock_Quantity;
                    productToUpdate.Model_Number = productDTO.Model_Number;
                    productToUpdate.Product_Attributes_Id = productDTO.Product_Attributes_Id;
                    productToUpdate.Product_Category_Id = productDTO.Product_Category_Id;
                    productToUpdate.Product_Code = productDTO.Product_Code;
                    productToUpdate.Product_Expiry_Date = productDTO.Product_Expiry_Date;
                    productToUpdate.Product_Image = productDTO.Product_Image;
                    productToUpdate.Product_Name = productDTO.Product_Name;
                    productToUpdate.Remarks = productDTO.Remarks;
                    productToUpdate.Unit_Id = productDTO.Unit_Id;
                    productToUpdate.Unit_Price = productDTO.Unit_Price;

                    // 使用 SqlSugar 的 Updateable 方法更新用户对象
                    _db.Updateable(productToUpdate).ExecuteCommand();

                    return new APIResult<ProductDTO>
                    {
                        Code = 200,
                        Data = productDTO,
                        Message = "修改成功",
                        ids = _db.Updateable(productToUpdate).ExecuteCommand(),
                    };
                }
                else
                {
                    apiResult.Code = 404; // 用户不存在
                    apiResult.Message = "入库信息不存在，无法更新";
                }

                return apiResult;
            }
            catch (Exception ex)
            {
                apiResult.Code = 500; // 服务器内部错误
                apiResult.Message = "更新入库出错：" + ex.Message;
                return apiResult;
            }
        }
    }
}
